package com.rainliang.project.util; 

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class StringUtil  {
	protected static Log logger = LogFactory.getLog(StringUtil.class);
	
	public static Float toMoney(String s){
		if (s==null) return 0f;
		if (s.indexOf(".")!=-1){
			
			if(s.indexOf(".") == 0){
				s = "0" + s;
			}
			 
			s += "00"; 
			s = s.substring(0, s.indexOf(".")+3);
		}
		Float fl = toFloat(s);
		if (fl == null) fl = 0f;
		return fl;
	} 
	
	public static Float toFloat(String s){
		if (s==null||"".equals(s.trim()))
			return null;
		try {
			return Float.parseFloat(s.trim()); 
		}catch(NumberFormatException nfe) {
			return null; 
		}
	}
	
	public static Double toDouble(String s){
		if (s==null||"".equals(s.trim()))
			return null;
		try {
			return Double.parseDouble(s.trim());
		}catch(NumberFormatException nfe) {
			return null; 
		}
	}
	public static Float toFloat(String s,Float defaultValue){
		if (s==null||"".equals(s.trim()))
			return defaultValue;
		try {
			return Float.parseFloat(s.trim()); 
		}catch(NumberFormatException nfe) {
			return defaultValue; 
		}
	}
	public static Double toDouble(String s,Double defaultValue){
		if (s==null||"".equals(s.trim()))
			return defaultValue;
		try {
			return Double.parseDouble(s.trim());
		}catch(NumberFormatException nfe) {
			return defaultValue; 
		}
	}

	public static Integer toInteger(String s){
		return toInteger(s , null);
	}
	
	public static Integer toInteger(String s,Integer defaultValue){
		if (s==null||"".equals(s.trim()))
			return defaultValue;
		try {
			return Integer.parseInt(s.trim()); 
		}catch(NumberFormatException nfe) {
			return defaultValue; 
		}
	}
	public static Long toLong(String s){
		return toLong(s , null);
	}
	
	public static Long toLong(String s,Long defaultValue){
		if (s==null||"".equals(s.trim()))
			return defaultValue;
		try {
			return Long.parseLong(s.trim()); 
		}catch(NumberFormatException nfe) {
			return defaultValue; 
		}
	}
	
	public static boolean isInt(String id) {
		if(id == null) 
			return false; 
		try {
			Integer.parseInt(id.trim()); 
		} catch(NumberFormatException nfe) {
			return false; 
		}
		return true; 
	}
	public static boolean isId(String id) {
		if(id == null) 
			return false; 
		try {
			int intValue = Integer.parseInt(id.trim()); 
			if(intValue <= 0)
				return false; 
		} catch(NumberFormatException nfe) {
			return false; 
		}
		return true; 
	}	
	public static boolean isIntWithRightSize(String id, int size) {
		if(id == null) 
			return false; 
		try {
			String tempStr=id.trim();  
			Integer.parseInt(id.trim()); 
			if(tempStr.length() > size) 
				return false; 
		} catch(NumberFormatException nfe) {
			return false; 
		}
		return true; 
	}
	
	public static boolean isEmpty(String str) {
		if(str == null) 
			return true; 
		String tempStr = str.trim(); 
		if(tempStr.length() == 0)
			return true; 
		if(tempStr.equals("null"))
			return true;
		return false; 
	}

	public static boolean isIndicator(String str) {
		if(str == null) 
			return false; 
		String tempStr = str.trim(); 
		if(tempStr.length() != 1)
			return false; 
		return true; 
	}
	
	public static String convertStringArrayToStringWithParser(String []inputStringArray, String parser) {
		if(inputStringArray == null || parser == null)
			return null; 
		StringBuffer buffer = new StringBuffer();
		for(int i=0; i<inputStringArray.length; i++) {
			buffer.append(inputStringArray[i]).append(parser); 
		}
		int bufferLength = buffer.length(); 
		StringBuffer newBuffer = buffer.deleteCharAt(bufferLength-1); 
		return newBuffer.toString(); 
	}	
	
	public static List parseStringToList(String inputString, String parserString) {
		if (inputString == null)
			return null;

		StringTokenizer st = new StringTokenizer(inputString, parserString);
		ArrayList result = new ArrayList(20);

		while (st.hasMoreTokens())
			result.add(st.nextToken().trim());

		return result;
	}
	
	public static Set parseStringToSet(String inputString, String parserString) {
		if (inputString == null)
			return null;

		StringTokenizer st = new StringTokenizer(inputString, parserString);
		Set set = new HashSet(10);

		while (st.hasMoreTokens()) {
			set.add(st.nextToken().trim());
		}
		return set;
	}
	
	public static String getFirstItemString(String inputString, String parserString) {
		if (inputString == null)
			return null;

		String result = null;
		StringTokenizer st = new StringTokenizer(inputString, parserString);

		if (st.hasMoreTokens())
			result = st.nextToken().trim();

		return result;
	}

	public static String getLastItemString(String inputString, String parserString) {
		int lastIndex = inputString.lastIndexOf(parserString);

		return inputString.substring(lastIndex + parserString.length());
	}

	public static String removeFirstItemFromString(String inputString, String parserString) {
		int index = inputString.indexOf(parserString);
		if (index < 0)
			return null;
		else
			return inputString.substring(index + parserString.length());
	}

	public static boolean isPatternInString(String targetString, String stringPattern) {
		if (targetString == null || stringPattern == null)
			return false;

		if (targetString.toLowerCase().indexOf(stringPattern.toLowerCase()) < 0)
			return false;

		return true;
	}
	
	public static String replace(String str, String pattern, String replace) {
	    int s = 0;
	    int e = 0;
	    StringBuffer result = new StringBuffer();
	
	    while ((e = str.indexOf(pattern, s)) >= 0) {
	        result.append(str.substring(s, e));
	        result.append(replace);
	        s = e+pattern.length();
	    }
	    result.append(str.substring(s));
	    return result.toString();
	}	

	public static String generateRandomString( int length, int seed ) {
		StringBuffer sb = new StringBuffer();
		Random r = new Random( System.currentTimeMillis() + seed );
		int i = 0;
		while( i++ < length ) {
			int randomNumber = r.nextInt( 62 );
			if( randomNumber >=0 && randomNumber <=9 ) {
				sb.append( (char)(randomNumber + 48) );
			} else if( randomNumber >= 10 && randomNumber <= 35 ) {
				sb.append( (char)(randomNumber + 55) );
			} else if( randomNumber >= 36 && randomNumber <= 61 ) {
				sb.append( (char)(randomNumber + 61) );
			}
		}
		return sb.toString();
	}

    public static String getIdString(int[] idArray) {
    	StringBuffer buffer = new StringBuffer(idArray.length*2); 
    	for(int i=0; i<idArray.length; i++) {
    		buffer.append(idArray[i]).append(",");  
    	}
    	int length = buffer.length(); 
    	int lastCommaIndex = buffer.lastIndexOf(","); 
    	if(length == (lastCommaIndex+1))
    		return buffer.substring(0, length-1); 
    	else
    		return buffer.toString(); 
    }

	public static String removeWhiteSpace(String str) {
		String res = null;
		
		if( str != null ) {
			char[] chars = str.toCharArray();
			res = "";
			
			for( int i = 0; i < chars.length; ++i ) {
				if( !Character.isWhitespace(chars[i]) ) {
					res += chars[i];
				}
			}
		}
		
		return res;
	}
	
	public static String removeFormattingCharacters(String str){
		String res = null;
		
		if( str != null ) {
			char[] chars = str.toCharArray();
			res = "";
			
			for( int i = 0; i < chars.length; ++i ) {
				if( Character.isLetterOrDigit(chars[i]) ) {
					res += chars[i];
				}
			}
		}
		
		return res;		
		
		
	}
	
	
	public static byte[] encodeBase64(String str)  {
		if( str == null ) { return null; }
		
		BASE64Encoder enc = new BASE64Encoder();
		String encode = enc.encode(str.getBytes());
		
		return encode.getBytes();
	}
	
	public static String decodeBase64(byte[] bytes) throws IOException {
		if( bytes == null ) { return null; }
		
		BASE64Decoder dec = new BASE64Decoder();
		ByteArrayInputStream biis = new ByteArrayInputStream(bytes);
		byte[] decode = dec.decodeBuffer(biis);
		
		String utf8 = new String(decode);
		
		return utf8;
	}
	
	public static String normalizePhoneNumber( String phoneNumber ) {
		// strip out anything that's not 0-9
		String phone = phoneNumber.replaceAll( "[^0-9]", "" );
		phone = phone.replaceAll( "[\\s]", "" );
//		if( !phone.startsWith( "1" ) && !phone.startsWith( "0" ) ) {
//			phone = "1" + phone;
//		}
//		if(phone.length()>10 && (phone.startsWith("1") || phone.startsWith("0")))
//			phone = phone.substring(1); 
		return phone;
	}
	
	
	public static String replaceIgnoreCase(String string,String word,String start,String end) {
		if (word==null || word.length()==0) return string;
		Pattern pattern=Pattern.compile(word.toLowerCase());
		Matcher matcher=pattern.matcher(string.toLowerCase());
		StringBuffer buffer=new StringBuffer();
		int index=0;
		while (matcher.find()) {
			buffer.append(string.substring(index,matcher.start()));
			buffer.append(start);
			buffer.append(string.substring(matcher.start(),matcher.end()));
			buffer.append(end);
			index=matcher.end();
		}
		buffer.append(string.substring(index));
		return new String(buffer);
	}
	public static String mySubStringRename(String filePath){
		String name="";
		java.io.File file=new java.io.File(filePath);
		name=file.getName();
		String path="";
		path=file.getPath();
			
		int i=name.indexOf('.');
		String nameTemp="FileName";//文件名太长,所以改成固定文件名
		if (i>0) {
			nameTemp+='_'+getDate()+name.substring(i,name.length());
		} else {
			nameTemp+=getDate();
		}
		return path+name;
	}
	
	public static String getDate(){
		 GregorianCalendar   g=new   GregorianCalendar(); 
		 String year= String.valueOf(g.get(GregorianCalendar.YEAR));
		 String month= String.valueOf(g.get(GregorianCalendar.MONTH)+1);
		 String day= String.valueOf(g.get(GregorianCalendar.DAY_OF_MONTH));
		 String hour=String.valueOf(g.get(GregorianCalendar.HOUR_OF_DAY));
		 String minute=String.valueOf(g.get(GregorianCalendar.MINUTE));
		 String second=String.valueOf(g.get(GregorianCalendar.SECOND));
		 
		 if(month.length()<2){
			 month="0"+month;
		 }
		 if(day.length()<2){
			 day="0"+day;
		 }
		 if(hour.length()<2){
			 hour="0"+hour;
		 }
		 if(minute.length()<2){
			 minute="0"+minute;
		 }
		 if(second.length()<2){
			 second="0"+second;
		 }
		 //System.out.println(year+month+day+"_"+hour+minute+second);
		 return year+month+day+"_"+hour+minute+second;
	}
	public static String getDate1(){
		 GregorianCalendar   g=new   GregorianCalendar(); 
		 String year= String.valueOf(g.get(GregorianCalendar.YEAR));
		 String month= String.valueOf(g.get(GregorianCalendar.MONTH)+1);
		 String day= String.valueOf(g.get(GregorianCalendar.DAY_OF_MONTH));
		 String hour=String.valueOf(g.get(GregorianCalendar.HOUR_OF_DAY));
		 String minute=String.valueOf(g.get(GregorianCalendar.MINUTE));
		 String second=String.valueOf(g.get(GregorianCalendar.SECOND));
		 
		 if(month.length()<2){
			 month="0"+month;
		 }
		 if(day.length()<2){
			 day="0"+day;
		 }
		 
		 return year+"-"+month+"-"+day;
	}

	public static String getString(String s){
		if(isEmpty(s)){
			return "";
		}else{
			return s.trim();
		}
	}

    public static String toGBK(String str){
        try
        {
                if(str==null)
                        str = "";
                else{
                	str=str.trim();
                	//str=toHtmlInput(str);
                	str=new String(str.getBytes("ISO-8859-1"),"utf-8");
                }
                
        }
        catch (Exception ex) {
        	//com.wantuan.util.LogUtil.dealWith(ex,StringUtil.class);
        	ex.printStackTrace();
        }
        return str;
    }
    
    public static String toGBKExceptSpace(String str){
        try
        {
                if(str==null)
                        str = "";
                else{
                	//str=toHtmlInputExceptSpace(str);
                	str=new String(str.getBytes("ISO-8859-1"),"utf-8");
                }
                
        }
        catch (Exception ex) {
        	//com.wantuan.util.LogUtil.dealWith(ex,StringUtil.class);
        	ex.printStackTrace();
        }
        return str;
    }
        
    
    /*分割字符串*/
    public static String[] splitStr(String str,char c)
    {
    	try {
    		str+=c;
    		int n=0;
    		for(int i=0;i<str.length();i++)
    		{
    			if(str.charAt(i)==c)n++;
    		}
    		
    		String out[] = new String[n];
    		
    		for(int i=0;i<n;i++)
    		{
    			int index = str.indexOf(c);
    			out[i] = str.substring(0,index);
    			str = str.substring(index+1,str.length());
    		}
    		return out;
			
		} catch (Exception e) {
		}
		return null;
    }
    
    public static String UrlDecoder(String url){
    	try {
    		if(url!=null){
    			return URLDecoder.decode(url,"UTF-8");
    		}else{
    			return null;
    		}
    		
		}catch(IllegalArgumentException e){
			try{
				return URLDecoder.decode(url,"GBK");
			}catch(UnsupportedEncodingException ex){
				return null;
			}catch(IllegalArgumentException ex){
				logger.error("url Decoder error : " + url);
				return null;
			}
		}
		catch (UnsupportedEncodingException ex) {
			return null;
		}  	
    }
    
    public static String UrlDecoderGBK(String url){
    	try {
    		if(url!=null){
    			return URLDecoder.decode(url,"GBK");
    		}else{
    			return null;
    		}
    		
		} catch (UnsupportedEncodingException ex) {
			//com.wantuan.util.LogUtil.dealWith(ex,StringUtil.class);
			return null;
		}  	
    }
    
    public static String UrlEncoder(String url){
    	try {
    		if(url==null) url = "";
			String tmp= URLEncoder.encode(url,"UTF-8");
			return tmp;
		} catch (UnsupportedEncodingException ex) {
			//com.wantuan.util.LogUtil.dealWith(ex,StringUtil.class);
			return null;
		}  	
    }
    
    public static String UrlEncoder1(String url){
    	try {
    		if(url==null) url = "";
			String tmp= URLEncoder.encode(url,"UTF-8");
			return tmp;
		} catch (UnsupportedEncodingException ex) {
			//com.wantuan.util.LogUtil.dealWith(ex,StringUtil.class);
			return null;
		}  	
    }
    /**
     * 字符串替换，将 source 中的 oldString 全部换成 newString
     *
     * @param source 源字符串
     * @param oldString 老的字符串
     * @param newString 新的字符串
     * @return 替换后的字符串
     */
    public static String replaceStr(String source, String oldString, String newString) {
        StringBuffer output = new StringBuffer();

        int lengthOfSource = source.length();   // 源字符串长度
        int lengthOfOld = oldString.length();   // 老字符串长度

        int posStart = 0;   // 开始搜索位置
        int pos;            // 搜索到老字符串的位置
        
        String lower_s=source.toLowerCase();		//不区分大小写
        String lower_o=oldString.toLowerCase();
        
        while ((pos = lower_s.indexOf(lower_o, posStart)) >= 0) {
            output.append(source.substring(posStart, pos));

            output.append(newString);
            posStart = pos + lengthOfOld;
        }

        if (posStart < lengthOfSource) {
            output.append(source.substring(posStart));
        }

        return output.toString();
    }


	/**
	 * 2007-7-30 added by lxs
	 * 将原有的字符串按照需要的长度显示,超出的长度用..代替。
	 * 给定的长度应包含2位..的长度数。
	 *0x3400->13312->'?' 0x9FFF->40959->? 0xF900->63744->?
	 */

	public static String getLeftStr(String str,int length){
		if(str == null || "".equals(str)){
			return "";
		}
		int index = 0;
		int strLength = str.length();
//		if (length>strLength) 
//			length = strLength;
		if (length<0)
			length=0;
	
//		System.out.println("getLeftStr length = " + length);
		char[] charArray = str.toCharArray();
		//希腊字母表使用从0x0370到0x03FF的代码，斯拉夫语使用从0x0400到0x04FF的代码，美国使用从0x0530到0x058F的代码，希伯来语使用从0x0590到0x05FF的代码。
		//中国、日本和韩国的象形文字（总称为CJK）占用了从0x3000到0x9FFF的代码。
		for(;index<length; index++){
			if (index >= strLength){
				break;
			}
			if(((charArray[index]>=0x3000)&&(charArray[index]<0x9FFF))||(charArray[index]>=0xF900)){
				length --;
//				System.out.println("length = " + length);
			}
			if (charArray[index]=='&'){
				//&lt;
				if (strLength>(index+3) && charArray[index+1]=='l' && charArray[index+2]=='t' && charArray[index+3]==';'){
					length += 3 ;
					index +=3;
				}
				//&#46;
				if(strLength>(index+4) && charArray[index+1]=='#' && charArray[index+2]=='4' && charArray[index+3]=='6' && charArray[index+4]==';' ){
					length += 4 ;
					index += 4 ;
				}
				//&nbsp;
				if (strLength>(index+5) && charArray[index+1]=='n' && charArray[index+2]=='b' && charArray[index+3]=='s' && charArray[index+4]=='p' && charArray[index+5]==';'){
					length += 5 ;
					index += 5 ;
				}
				//&quot;
				if (strLength>(index+5) && charArray[index+1]=='q' && charArray[index+2]=='u' && charArray[index+3]=='o' && charArray[index+4]=='t' && charArray[index+5]==';'){
					length += 5 ;
					index += 5 ;
				}
				//&acute;
				if (strLength>(index+6) && charArray[index+1]=='a' && charArray[index+2]=='c' && charArray[index+3]=='u' && charArray[index+4]=='t' && charArray[index+5]=='e' && charArray[index+6]==';'){
					length += 6 ;
					index += 6 ;
				}
				//&cedil;
				if (strLength>(index+6) && charArray[index+1]=='c' && charArray[index+2]=='e' && charArray[index+3]=='d' && charArray[index+4]=='i' && charArray[index+5]=='l' && charArray[index+6]==';'){
					length += 6 ;
					index += 6 ;
				}
//				if (length>strLength) 
//					length = strLength;
			}
		}
//		System.out.println("index = " + index);
		String returnStr = str.substring(0, index);

		returnStr += "..";
		return returnStr;
	}
	

    /**
     * 将字符串格式化成 HTML 代码输出
     * 只转换特殊字符，适合于 HTML 中的表单区域
     *
     * @param str 要格式化的字符串
     * @return 格式化后的字符串
     */
    public static String toHtmlInput(String html){     
	    if (StringUtil.isEmpty(html)){
	    	return html;
	    }
	     html = replaceStr(html, "<", "&lt;");
	     html = replaceStr(html, ">", "&gt;");
	     html = replaceStr(html, "/", "&#47;");
	     html = replaceStr(html, "\r\n", "<br/>");
	     html = replaceStr(html, "\\", "&#92;");
	     html = replaceStr(html,"'","&acute;");
	     html = replaceStr(html,"\"","&quot;");
	     html = replaceStr(html,".","&#46;");
	     html = replaceStr(html,"(","&#40;");
	     html = replaceStr(html,")","&#41;");
	     
	   	 return html;
   }
    
    
    public static String toHtmlOutput(String str) {
	    if (str == null)    return null;
	
	    String html = new String(str);
	    
	    html = replaceStr(html, "&#47;","/");
	    html = replaceStr(html, "&#92;","\\");
	    html = replaceStr(html, "<br>","\r\n");
	    html = replaceStr(html, "<br/>","\r\n");
	    html = replaceStr(html, "&lt;","<");
        html = replaceStr(html, "&gt;", ">");
        html = replaceStr(html, "    ","\t" );
        html = replaceStr(html, "&nbsp;"," "); 
        html = replaceStr(html, "&acute;","'");
        html = replaceStr(html, "&quot;","\"");
        html = replaceStr(html, "&cedil;",".");
        html = replaceStr(html, "&#46;",".");
        html = replaceStr(html, "&#40;", "(");
        html = replaceStr(html, "&#41;", ")");
	
	    return html;
    }
    
     
    public static String toBssOutput(String str){
    	if (str == null)    return "";
    	
	    String html = new String(str);
	    html=toHtmlOutput(html);
	    html = replaceStr(html, "&gt;",">");
	    html = replaceStr(html, "<iframe","< iframe");
	    html = replaceStr(html, "</iframe","< /iframe");
	    html = replaceStr(html, "<script","< script");
	    html = replaceStr(html, "</script","< /script");
	    html = replaceStr(html, "<embed","< embed");
	    html = replaceStr(html, "</embed","< /embed");
	    html = replaceStr(html, "<link","< link");
	    html = replaceStr(html, "</link","< /link");
	    html = replaceStr(html, "</body", "< /body");
	    html = replaceStr(html, "onload", "");
		
	    return html;
    }
    
    public static String htmlToStr(String htmlStr) {
		String result = "";
		boolean flag = true;
		if (htmlStr == null) {
			return null;
		}
		char[] a = htmlStr.toCharArray();
		int length = a.length;
		for (int i = 0; i < length; i++) {
			if (a[i] == '<') {
				flag = false;
				continue;
			}
			if (a[i] == '>') {
				flag = true;
				continue;
			}
			if (flag == true) {
				result += a[i];
			}
		}
		return result.toString();
	} 
    /**
	 * 过滤html标签
	 * @param htmlStr
	 * @param length
	 * @return
	 */
	 public static String htmlToStr(String htmlStr,int length) {
		if (htmlStr == null) {
			return "";
		}
		StringBuffer result = new StringBuffer();
		int count = 0;
		
		boolean flag = true;
		htmlStr = htmlStr.replace("&lt;", "<");
		char[] a = htmlStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			if (a[i] == '<') {
				flag = false;
				continue;
			}
			if (a[i] == '>') {
				flag = true;
				continue;
			}
			if (flag == true) {
				count++;
			}
			if(count > length){
				result.append("...");
				break;
			}
			if(flag == true){
				result.append(a[i]);
			}
		}
		return result.toString();
	} 
    
    //  全角转半角
	public static String SBCchange(String str){
		String outStr = "";
		byte[] b = null;
		try{
			for(int i=0;i<str.length();i++){
				b = str.substring(i,i+1).getBytes("unicode");
				if(b[3]==-1){
					b[2] = (byte)(b[2]+32);
					b[3] = 0;
					outStr += new String(b,"unicode");
				}else{
					outStr += str.substring(i,i+1);
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return outStr;
	}
	
	//半角转全角
	public static String BQchange(String str){
		String outStr = "";
		byte[] b = null;
		try{
			for(int i=0;i<str.length();i++){
				b = str.substring(i,i+1).getBytes("unicode");
				if(b[3]!=-1){
					b[2] = (byte)(b[2]-32);
					b[3] = -1;
					outStr += new String(b,"unicode");
				}else{
					outStr += str.substring(i,i+1);
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return outStr;
	}
    
	public static long getIpValue(String ip){
		try{
			String[] str=splitStr(ip,'.');
			return Long.valueOf(str[0])*256*256*256+Long.valueOf(str[1])*256*256+Long.valueOf(str[2])*256+Long.valueOf(str[3]);
		}catch(Exception ex){
			return 0;
		}
	}
	
	
	
}

